const user = require("../sql/user");
const md5 = require("md5")
module.exports = function(){
  return async (req,res,next)=>{
    // 接收前端发送的老新密码
    const {opassword, npassword} = req.body;
    // 根据当前登录的用户，读取用户信息
    const data = await user.find( {
      userId: req.userMsg.userId
    } )
    // 判断老密码是否正确
    if(data[0].password === md5(opassword)){
      // 老密码正确，修改密码
      try{
        await user.updateOne({
          userId: req.userMsg.userId
        }, {
          password: md5(npassword)
        })
        res.send({state:0, msg:"修改成功"})
      }catch(err){
        res.send({state:2, msg:"修改失败"})
      }
    }else{
      // 老密码不对
      res.send({state:1, msg:"老密码不对"});
    }
  }
}